package com.summer.framework.core.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.summer.framework.base.constant.FieldConstant;
import com.summer.framework.core.context.UserContext;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

/**
 * Description:
 * @auther Ice Yang
 * Date 2025/7/3 17:02
 */
@Component
public class SummerMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        // 自动填充创建信息
        this.strictInsertFill(metaObject, FieldConstant.CREATE_TIME, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, FieldConstant.CREATE_NAME, String.class, getCurrentUsername());
        this.strictInsertFill(metaObject, FieldConstant.CREATE_ID, Long.class, getCurrentUserId());

        // 更新信息在插入时也初始化
        this.strictInsertFill(metaObject, FieldConstant.UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, FieldConstant.UPDATE_NAME, String.class, getCurrentUsername());
        this.strictInsertFill(metaObject, FieldConstant.UPDATE_ID, Long.class, getCurrentUserId());

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        // 自动填充更新信息
        this.strictInsertFill(metaObject, FieldConstant.UPDATE_TIME, LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, FieldConstant.UPDATE_NAME, String.class, getCurrentUsername());
        this.strictInsertFill(metaObject, FieldConstant.UPDATE_ID, Long.class, getCurrentUserId());
    }

    /**
     * 获取当前操作用户
     */
    private String getCurrentUsername() {
        return UserContext.getUserName() == null ? "system" : UserContext.getUserName();
    }

    /**
     * 获取当前操作用户
     */
    private Long getCurrentUserId() {
        return UserContext.getUserId() == null ? 0L : UserContext.getUserId();
    }
}
